﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using PJ.Business;
using Microsoft.Practices.Composite.Presentation.Commands;
using Microsoft.Practices.Composite.Events;

namespace PJ.Presentation
{
    public abstract class SearchModel : BaseViewModel, ISearchModel
    {
        protected readonly IItemService m_Service;

        protected IItemService Service
        {
            get
            {
                if (m_Service == null)
                    throw new ArgumentNullException();
                return m_Service;
            }
        }

        protected SearchModel(IView view, IEventAggregator aggregator, IItemService service)
            : base(view, aggregator)
        {
            m_Service = service;
            SearchCommand = new DelegateCommand<object>(OnSearch, OnCanSearch);
        }

        public abstract void OnSearch(object sender);

        protected bool OnCanSearch(object sender)
        {
            //if (string.IsNullOrEmpty(SearchText))
            //    return false;
            //else
                return true;
        }

        public DelegateCommand<object> SearchCommand
        { get; set; }

        public string SearchText
        {
            get
            {
                return (string)ThreadUnsafeGetValue(SearchTextProperty);
            }
            set
            {
                ThreadUnsafeSetValue(SearchTextProperty, value);
            }
        }

        public static readonly DependencyProperty SearchTextProperty =
            DependencyProperty.Register("SearchText", typeof(string), typeof(SearchModel), new UIPropertyMetadata(""));

        public IEnumerable<string> Search(string searchTxt)
        {
            return Service.Search(searchTxt, PJ.Data.GetDataMode.CachedFind);
        }
    }
}
